package com.loong.order.util;

/**
 * @Description:
 * @Author: hzp
 * @Date: 2021-1-7 11:17
 */

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 缓存工具
 */
@Slf4j
public class ConcurrentHashMapCacheUtils {
    /**
     * 当前缓存个数
     */
    public static Integer CURRENT_SIZE = 0;
    /**
     * 时间一分钟
     */
    static final Long ONE_MINUTE = 60 * 1000L;
    /**
     * 缓存超时
     */
    private static final Long TTL_TIME = 60 * 1000L;
    /**
     * 缓存对象
     */
    private static final ConcurrentHashMap<String, CacheObj> CACHE_OBJECT_MAP = new ConcurrentHashMap<>();
    /**
     * 清理过期缓存是否在运行
     */
    private static volatile Boolean CLEAN_THREAD_IS_RUN = false;

    /**
     * 设置缓存
     */
    public static void setCache(String cacheKey, String cacheValue, long cacheTime) {
        Long ttlTime = null;
        if (cacheTime <= 0L) {
            if (cacheTime == -1L) {
                ttlTime = -1L;
            } else {
                return;
            }
        }
        CURRENT_SIZE = CURRENT_SIZE + 1;
        if (ttlTime == null) {
            ttlTime = System.currentTimeMillis() + cacheTime;
        }
        CacheObj cacheObj = new CacheObj(cacheValue, ttlTime);
        CACHE_OBJECT_MAP.put(cacheKey, cacheObj);
    }

    /**
     * 设置缓存
     */
    public static void setCache(String cacheKey, String cacheValue) {
        setCache(cacheKey, cacheValue, TTL_TIME);
    }

    public static long getCurrentSize() {
        return CACHE_OBJECT_MAP.mappingCount();
    }

    public static List<String> getRecentApp() {
        List<String> list = new ArrayList<>(16);
        for (String key : CACHE_OBJECT_MAP.keySet()) {
            list.add(key);
        }
        return list;
    }

    /**
     * 获取缓存
     */
    public static String getCache(String cacheKey) {
        startCleanThread();
        if (checkCache(cacheKey)) {
            return CACHE_OBJECT_MAP.get(cacheKey).getCacheValue();
        }
        return null;
    }

    /**
     * 删除某个缓存
     */
    public static void deleteCache(String cacheKey) {
        Object cacheValue = CACHE_OBJECT_MAP.remove(cacheKey);
        if (cacheValue != null) {
            CURRENT_SIZE = CURRENT_SIZE - 1;
        }
    }

    /**
     * 判断缓存在不在,过没过期
     */
    private static boolean checkCache(String cacheKey) {
        CacheObj cacheObj = CACHE_OBJECT_MAP.get(cacheKey);
        if (cacheObj == null) {
            return false;
        }
        if (cacheObj.getTtlTime() == -1L) {
            return true;
        }
        if (cacheObj.getTtlTime() < System.currentTimeMillis()) {
            deleteCache(cacheKey);
            return false;
        }
        return true;
    }

    /**
     * 删除过期的缓存
     */
    static void deleteTimeOut() {
        List<String> deleteKeyList = new LinkedList<>();
        for (Map.Entry<String, CacheObj> entry : CACHE_OBJECT_MAP.entrySet()) {
            if (entry.getValue().getTtlTime() < System.currentTimeMillis() && entry.getValue().getTtlTime() != -1L) {
                deleteKeyList.add(entry.getKey());
            }
        }
        for (String deleteKey : deleteKeyList) {
            deleteCache(deleteKey);
        }
    }

    /**
     * 设置清理线程的运行状态为正在运行
     */
    static void setCleanThreadRun() {
        CLEAN_THREAD_IS_RUN = true;
    }

    /**
     * 开启清理过期缓存的线程
     */
    private static void startCleanThread() {
        if (!CLEAN_THREAD_IS_RUN) {
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("clean-cache-pool-").build();
            ThreadPoolExecutor cleanThreadPool = new ThreadPoolExecutor(8, 16, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(8), namedThreadFactory);
            cleanThreadPool.execute(new CleanTimeOutThread());
        }
    }
}

class CacheObj {
    /**
     * 缓存对象
     */
    private String cacheValue;
    /**
     * 缓存过期时间
     */
    private Long ttlTime;

    CacheObj(String cacheValue, Long ttlTime) {
        this.cacheValue = cacheValue;
        this.ttlTime = ttlTime;
    }

    String getCacheValue() {
        return cacheValue;
    }

    Long getTtlTime() {
        return ttlTime;
    }

    @Override
    public String toString() {
        return "CacheObj {" + "cacheValue = " + cacheValue + ", ttlTime = " + ttlTime + '}';
    }
}

/**
 * 每一分钟清理一次过期缓存
 */
@Slf4j
class CleanTimeOutThread implements Runnable {


    @Override
    public void run() {
        ConcurrentHashMapCacheUtils.setCleanThreadRun();
        while (true) {
            ConcurrentHashMapCacheUtils.deleteTimeOut();
            try {
                Thread.sleep(ConcurrentHashMapCacheUtils.ONE_MINUTE);
            } catch (InterruptedException e) {
                log.error("Time-out Cache has not been cleaned!{}", e.getMessage());
            }
        }
    }
}
